package swu.core;

import org.apache.commons.dbcp2.BasicDataSource;
import swu.commodity.Commodity;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class ObjectRepo
{
    private static BasicDataSource dataSource;

    static
    {
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e)
        {
            throw new RuntimeException(e);
        }
        dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/shopping_mall?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("slxc20040913");

        dataSource.setMinIdle(5);
        dataSource.setMaxIdle(10);
        dataSource.setMaxTotal(20);
        dataSource.setInitialSize(5);
    }

    public static Connection getConnection() throws SQLException
    {
        return dataSource.getConnection();
    }

    public void queryAll(String sql,ResultSetIterator iterator) throws SQLException
    {
        try(Connection connection = getConnection())
        {
            try(Statement statement = connection.createStatement())
            {
                ResultSet resultSet = statement.executeQuery(sql);
                while(resultSet.next())
                {
                    iterator.visit(resultSet);
                }
            }
        }
    }

    public void executeSQL(String sql) throws SQLException
    {
        try(Connection connection = getConnection())
        {
            try(Statement statement = connection.createStatement())
            {
                statement.execute(sql);
            }
        }
    }

    public static List<Commodity> handler(ResultSet rs, Class<?> clazz)
    {
        List<Commodity> list = new ArrayList<>();
        Commodity obj = null;
        try
        {
            while (rs.next())
            {

                obj = (Commodity) clazz.newInstance();

                ResultSetMetaData rsmeta = rs.getMetaData();

                int count = rsmeta.getColumnCount();


                for (int i = 0; i < count; i++)
                {

                    String name = rsmeta.getColumnName(i + 1);

                    Field f = obj.getClass().getDeclaredField(name);
                    f.setAccessible(true);

                    f.set(obj, rs.getObject(name));
                }
                list.add(obj);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return list;
    }

}
